package com.douziit.meilianoa.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.douziit.meilianoa.base.annotation.NoCheckToken;
import com.douziit.meilianoa.base.exception.TipException;
import com.douziit.meilianoa.base.request.LoginRequest;
import com.douziit.meilianoa.base.request.PageRequest;
import com.douziit.meilianoa.base.response.Account.AccountResponse;
import com.douziit.meilianoa.base.response.ResponseData;
import com.douziit.meilianoa.base.response.ResponseUtil;
import com.douziit.meilianoa.base.utils.StrEncryptUtil;
import com.douziit.meilianoa.dto.AccountDto;
import com.douziit.meilianoa.dto.ProjectInfoRate;
import com.douziit.meilianoa.entity.Account;
import com.douziit.meilianoa.entity.Fees;
import com.douziit.meilianoa.entity.ProjectInfo;
import com.douziit.meilianoa.entity.TargetAmount;
import com.douziit.meilianoa.service.AccountService;
import com.douziit.meilianoa.service.FeesService;
import com.douziit.meilianoa.service.ProjectInfoService;
import com.douziit.meilianoa.service.TargetAmountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.RequestDate;
import org.hibernate.dialect.RDMSOS2200Dialect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.*;

/**
 *用户操作控制器
 */
@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private TargetAmountService targetAmountService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private  FeesService feesService;

    /**
     * PC登入
     * @return
     */
    @NoCheckToken
    @PostMapping("/loginPc")
    public ResponseData loginPc(@RequestBody LoginRequest req){
        //e10adc3949ba59abbe56e057f20f883e
        AccountResponse response=accountService.loginPc(req);
        response.setPassword("");
        return ResponseUtil.jsonSuccess(response);
    }

    /**
     *app登入
     */
    @NoCheckToken
    @PostMapping("/login")
    public ResponseData login(@RequestBody LoginRequest req){
        //e10adc3949ba59abbe56e057f20f883e
        AccountResponse response=accountService.login(req);
        response.setPassword("");
        return ResponseUtil.jsonSuccess(response);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public ResponseData logout(){
        accountService.loginOut();
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 添加账号
     */
    @PostMapping("/addAccount")
    public ResponseData addAccount(@RequestBody Account account){

        Account a=accountService.getOne(new QueryWrapper<Account>().eq("phone",account.getPhone()));
        if (a!=null){
            throw new TipException("此手机号已存在");
        }
        account.setPassword(StrEncryptUtil.md5(account.getPassword()));
        account.setAddTime(new Date());
        account.setStatus(0);
        accountService.save(account);
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 个人信息列表
     */
    @GetMapping("/accountDetail")
    public ResponseData accountDetail(@RequestParam("accountId") Integer accountId){

        Account account = accountService.getById(accountId);
        //未通过预算项目
        List<ProjectInfo> list = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",2));
        //未通过报销项目
        List<ProjectInfo> list1 = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",6));
        AccountDto accountDto = new AccountDto();
        BeanUtils.copyProperties(account, accountDto);
        accountDto.setNotpassBudget(list.size());
        accountDto.setNotpassReimbursement(list1.size());
        return ResponseUtil.jsonSuccess(accountDto);
    }

        /**
         * 用户列表
         * @return
         */
    @PostMapping("/listAccount")
    @NoCheckToken
    public ResponseData listAccount(){
        //列出所有账号
        List<Account> list=accountService.list();
        return ResponseUtil.jsonSuccess(list);
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public ResponseData changePassword(@RequestParam("accountId") Integer accountId,@RequestParam("oldPwd") String oldPwd,
                                       @RequestParam("newPwd") String newPwd){
        //找到对应的用户id
        Account account=accountService.getById(accountId);
        if(account==null){
            throw new TipException("无此用户id");
        }
        if(!account.getPassword().equals(StrEncryptUtil.md5(oldPwd))){
            throw new TipException("原密码错误!");
        }
        account.setPassword(StrEncryptUtil.md5(newPwd));
        accountService.updateById(account);
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 重置密码
     */
    @PostMapping("/resetPassword")
    public ResponseData resetPassword(@RequestBody LoginRequest req){

        Account account = new Account();
        account.setPassword(StrEncryptUtil.md5(req.getNewPwd()));
        account.setId(req.getAccountId());
        accountService.updateById(account);
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/changeAccount")
    public ResponseData changeAccount(@RequestBody Account account){
        List<Account> list=accountService.list(new QueryWrapper<Account>().eq("phone",account.getPhone()));
        if(list.size()>1){
            throw new TipException("该号码被占用");
        }
        accountService.updateById(account);
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/changeImg")
    public ResponseData changeAccount(@RequestParam("accountId") Integer accountId, @RequestParam("headImg") String headImg){
        Account account = new Account();
        account.setId(accountId);
        account.setHeadImg(headImg);
        accountService.updateById(account);
        return ResponseUtil.jsonSuccess(0);
    }


    /**
     * 删除用户
     */
    @PostMapping("/deleteAccount")
    public ResponseData deleteAccount(@RequestBody PageRequest req){
        accountService.removeById(req.getAccountId());
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 用户:禁用/启用
     *  flag : 0 启用  1:禁用
     */
    @PostMapping("/setStatus/{accountId}/{flag}")
    public ResponseData setStatus(@PathVariable(value = "accountId")Integer accountId,@PathVariable(value = "flag")Integer flag){

        Account account = accountService.getOne(new QueryWrapper<Account>().eq("id",accountId));
        if(account==null){
            throw new TipException("无此用户id");
        }
        account.setStatus(flag);
        accountService.updateById(account);
        return ResponseUtil.jsonSuccess(0);
    }

    /**
     * 列出目标金额
     */
    @PostMapping("/listTarAmount")
    public ResponseData listTarAmount(@RequestBody PageRequest req){
        List<TargetAmount> list=targetAmountService.list(new QueryWrapper<TargetAmount>()
                        .eq("account_id",req.getAccountId()));
        return ResponseUtil.jsonSuccess(list);
    }

    /**
     * 设置目标金额
     */
    @PostMapping("/setTarAmount")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData setTarAmount(@RequestBody List<TargetAmount> list){

        if(list.size()==0){
            throw new TipException("无添加记录");
        }
        //删除之前记录
        targetAmountService.delete(list.get(0).getAccountId());
        //添加目标金额
        targetAmountService.saveBatch(list);
        return ResponseUtil.jsonSuccess(0);

    }

    /**
     * 该账号下未通过的预算/未通过的报销
     * flag : 0:未通过预算  1:未通过报销
     */
    @GetMapping("/notPassBudgetCount")
    public ResponseData notPassBudgetCount(@RequestParam Integer accountId){

        //未通过预算项目
        List<ProjectInfo> list = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",2));
        //未通过报销项目
        List<ProjectInfo> list1 = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",6));
        Map<String,Integer> map = new HashMap<>();
        map.put("notpassBudget",list.size());
        map.put("notpassReimbursement",list1.size());
        return ResponseUtil.jsonSuccess(map);
    }


    /**
     * 该账号下未通过的预算/未通过的报销
     * flag : 0:未通过预算  1:未通过报销
     */
    @GetMapping("/notPassBudget/{flag}")
    public ResponseData notPassBudget(@PathVariable(value = "flag")Integer flag,@RequestParam Integer accountId){

        log.info(">>>>>>accountId:{}",accountId);
        List<ProjectInfo> list = new ArrayList<>();
        List<ProjectInfoRate> listProjectRate = new ArrayList<>();
        if(flag==0){
            list = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",2));
        }else if(1==flag){
            list = projectInfoService.list(new QueryWrapper<ProjectInfo>().eq("account_id",accountId).eq("status",6));
        }
        for(ProjectInfo p : list){
            ProjectInfoRate projectInfoRate = new ProjectInfoRate();
            BeanUtils.copyProperties(p, projectInfoRate);
            Fees f = feesService.getOne(new QueryWrapper<Fees>().eq("project_id",p.getId()).eq("rei_bug_flag",flag));
            if(f !=null){
                projectInfoRate.setRate(f.getRate());
            }
            listProjectRate.add(projectInfoRate);
        }
        return ResponseUtil.jsonSuccess(listProjectRate);
    }

    /**
     * 查找所有督导
     */
    @GetMapping("/listSupervisor")
    public ResponseData listSupervisor(){
        List<Account> accounts = accountService.list(new QueryWrapper<Account>().eq("role",3));
        return ResponseUtil.jsonSuccess(accounts);
    }

}
